public class Solution {
    public static void main(String[] args) {

    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode hair = new ListNode(0);
        hair.next = head;
        ListNode pre = hair;

        while (head != null) {
            ListNode tail = pre;
            // 查看剩余部分长度是否大于等于 k
            for (int i = 0; i < k; ++i) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            ListNode nex = tail.next;
            ListNode[] reverse = myReverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            // 把子链表重新接回原链表
            pre.next = head;
            tail.next = nex;
            pre = tail;
            head = tail.next;
        }

        return hair.next;
    }

    public ListNode[] myReverse(ListNode head, ListNode tail) {
        ListNode prev = tail.next;
        ListNode p = head;
        while (prev != tail) {
            ListNode nex = p.next;
            p.next = prev;
            prev = p;
            p = nex;
        }
        return new ListNode[]{tail, head};
    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}


/*与我的想法更符合*/
class Solution2 {
    /**
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */

    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode hair = new ListNode(-1);
        hair.next = head;

        ListNode pre = hair;
        ListNode tail;
        ListNode newHead;
        while(head != null) {
            ListNode cur = pre;
            for (int i = 0; i < k; ++i) {
                cur = cur.next;
                if (cur == null) return hair.next; /*这里与上一句的顺序别弄错*/

            }
            newHead = cur.next;

            tail = cur;
            ListNode[] reverse = reverseList(head, tail);

            pre.next = reverse[0];
            reverse[1].next = newHead;

            pre = reverse[1];
            head = newHead;

        }
        return hair.next;

    }

    /*与一般的链表反转一样*/
    public ListNode[] reverseList (ListNode head, ListNode tail) {
        ListNode pre = null;
        ListNode cur = head;
        tail.next = null;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return new ListNode[] {tail, head};
    }
}
